<template>
  <forms ref="forms" :config="config" @submit:forms="onsubmit" :btns="btns">
  </forms>
</template>

<script>
import s94Mjs from "s94-js";
import {ajax} from "@/js/api_tool.js";
import {decode_config} from "@/js/s94_tool.js";
import {iframe} from "@/js/tool";

export default {
  props: ['__iframe'],
  data(){
    let id = this.$get('id'), btns = undefined;
    let forms_config = {
      name: {label:'用户名', name:'name', type:id?'':'text_one', tips:'用户名，登录用，不可修改'},
      password: {label:'密码',name:'password',type:'text_one',value:'',tips:id?'为空表示保持原密码':''},
      nickname: {label:'昵称',name:'nickname',type:'text_one',value:'',tips:''},
      truename: {label:'真实姓名',name:'truename',type:'text_one',tips:''},
      head_img: {label:'头像',name:'head_img',type:'file_img',tips:'管理员头像，建议尺寸100*100'},
      admin_role_ids: {label:'角色',name:'admin_role_ids',type:'select_more',config:[],tips:''},
      phone: {label:'电话号码',name:'phone',type:'text_one',tips:'联系方式，手机号'},
      info: {label:'简介',name:'info',type:'text_more',tips:'简介、彰显个性和特点的一段话'},
      status: {label:'状态',name:'status',type:'radio_switch',config:["禁用","启用"],tips:'禁用的管理员无法登录'},
    }
    if (id){
      forms_config.create_time = {label:'创建时间',name:'create_time',tips:''};
    }
    if (this.$get('is_info')){
      s94Mjs.each(forms_config, function (row){ row.is_info = true; });
      forms_config.password.remove = true;
      btns = [];
    }
    return {
      id: id,
      btns: btns,
      config: forms_config,
    }
  },
  methods: {
    onsubmit(formData){
      let url = this.id ? `/admin/admin/edit?id=`+this.id : '/admin/admin/add';
      if (!formData.get('password')) formData.delete('password');
      ajax({url:url, method:'POST', data:formData}, (res)=>{
        if (this.__iframe){
          iframe.exe('admin/index', '$refs.list_url.list');
          iframe.hide('admin/edit');
          if (!this.id) this.$refs['forms'].init();
        }else {
          this.$router.push('index');
        }
      }, (res)=>{
        if (res.errors) this.$refs['forms'].errors = res.errors;
      })

    }
  },
  mounted() {
    let app = this;
    if (!this.__iframe) window['app'] = this;
    if (this.id) {
      ajax({url:'/admin/admin/info?id='+this.id, cache:true}, (res)=>{
        res.data['password']='';
        this.$refs['forms'].init(res.data);
        return false;
      }, ()=>{
        if (this.__iframe){
          iframe.remove('edit');
        }else {
          this.$router.push('index');
        }
      })
    }

    //其他初始化操作
    ajax({url:'/admin/admin_role/list?order[id]=asc',cache:true}, (res)=>{
      this.config.admin_role_ids.config = decode_config(res.data.list, {content_key:'name', value_key:'id'});;
      return false
    })
  }
}
</script>
